import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 86138
 * Date: 2024-11-26
 * Time: 17:48
 */
class demo2 {
    public static int[] intersection(int[] nums1, int[] nums2) {
        Arrays.sort(nums1);
        Arrays.sort(nums2);
        int[] intersection = new int[nums1.length + nums2.length];
        int index1 = 0, index2 = 0, index = 0;
        while (index1 < nums1.length && index2 < nums2.length) {
            int num1 = nums1[index1], num2 = nums2[index2];
            if (num1 == num2) {
                if (num1 != intersection[index - 1] || index == 0) {
                    intersection[index++] = num1;
                }

                index1++;
                index2++;
            } else if (num1 < num2) {
                index1++;
            } else {
                index2++;
            }
        }
        return Arrays.copyOfRange(intersection, 0, index);
    }


    public static void main(String[] args) {
        int[] num1 = {4,9,5};
        int[] num2 = {9,4,9,8,4};

        System.out.println(Arrays.toString(intersection(num1,num2)));
    }
}
